<template>
  <el-dialog :title="option.title" :visible.sync="option.isShow" width="70%" :close-on-click-modal="false"
    @open="openDialog" @close="closeDialog">
    <el-row :gutter="10">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-col :span="12" v-if="option.flag != 'add'">
          <el-form-item label="模板编号" prop="SCORETEMPLATEID">
            <el-input v-model="ruleForm.SCORETEMPLATEID" disabled size="small" placeholder="请输入模板名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模板名称" prop="SCORETEMPLATENAME">
            <el-input v-model="ruleForm.SCORETEMPLATENAME" :disabled="option.flag=='detail'" size="small"
              placeholder="请输入模板名称"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="业务类型" prop="BUSINESSTYPE">
            <el-input v-model="ruleForm.BUSINESSTYPE" size="small" :disabled="option.flag=='detail'"
              placeholder="请输入业务类型"></el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="渠道类型" prop="CHANNELTYPE">
            <el-select v-model="ruleForm.CHANNELTYPE" size="small" filterable clearable placeholder="请选择业务渠道">
                  <el-option v-for="item in option.channelOption" :key="item.FIELDKEY" :label="item.FIELDVALUE"
                    :value="item.FIELDKEY"></el-option>
                </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="评分项" prop="score">
            <div class="block">
              <el-cascader size="small" :disabled="option.flag=='detail'" @change="changeScore" v-model="ruleForm.score"
                :props="props" :options="option.options" clearable></el-cascader>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-table :data="tableData" border width="80%" style="margin-bottom:30px;" :span-method="objectSpanMethod">
            <el-table-column prop="SCOREMAJORITEMNAME" align="center" label="评分大项"></el-table-column>
            <el-table-column prop="SCOREMAJORITEMWEIGHT" align="center" label="大项权重">
              <template slot-scope="scope">
                <div>
                  <el-select size="mini" :disabled="option.flag=='detail'" v-model="scope.row.SCOREMAJORITEMWEIGHT">
                    <el-option v-for="item in 20" :key="item" :value="item*5" :label="item*5"></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="SCOREMINORTERMNAME" align="center" label="评分子项"></el-table-column>
            <el-table-column prop="SCOREMINORTERMWEIGHT" align="center" label="小项权重">
              <template slot-scope="scope">
                <div>
                  <el-select size="mini" :disabled="option.flag=='detail'" v-model="scope.row.SCOREMINORTERMWEIGHT">
                    <el-option v-for="item in 20" :key="item" :value="item*5" :label="item*5"></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="MINORTERMTYPE" label="小项类型" align="center" :formatter="dataFormat"></el-table-column>
            <el-table-column prop="SPECIALATTRIBUTE" label="评分子项属性" align="center" :formatter="dataFormat"></el-table-column>
            <!-- <el-table-column prop="SUBSIDIARYFIELDFS" label="特殊项分数" align="center"></el-table-column>
            <el-table-column prop="EXTRASCORE" label="额外分值" align="center"></el-table-column> -->
          </el-table>
        </el-col>
        <el-col :span="24" v-if="option.flag != 'detail'">
          <el-form-item>
            <el-button type="primary" size="mini" @click="submitForm('ruleForm')">保存</el-button>
            <el-button @click="resetForm('ruleForm')" size="mini">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </el-dialog>
</template>

<script>
  import request from "@/common/utils/requestQC";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import scoreDictionarySmallQuery from '@/message/QCManage/scoreTemplate/scoreDictionarySmall/scoreDictionarySmallQuery';
  import scoreDictionaryBigQuery from '@/message/QCManage/scoreTemplate/scoreDictionaryBig/scoreDictionaryBigQuery';
  import addTemp from "@/message/QCManage/scoreTemplate/scoreTemplate/scoreTemplateAdd";
  import updateTemp from "@/message/QCManage/scoreTemplate/scoreTemplate/scoreTemplateUpdate";

  export default {
    props: {
      option: Object
    },
    computed: {
      isShow: {
        get: function () {
          return this.option.isShow;
        },
        set: function (newValue) {
          this.option.isShow = newValue;
        }
      }
    },
    mounted() {},
    data() {
      return {
        "special": {
          '': '',
          '1': '打分',
          '2': '选择',
        },
        typeOption:{
          1:'标准项',
          // 2:'加分项',
          3:'致命项',
        },
        tableData: [],
        spanArr: [],
        props: {
          multiple: true,
        },
        ruleForm: {
          SCORETEMPLATEID: '',
          SCORETEMPLATENAME: '',
          // BUSINESSTYPE: '',
          // CHANNELTYPE: '',
          CREATIVEPERSON: this.$store.getters.UserNum, //创作人
          score: ''
        },
        rules: {
          SCORETEMPLATENAME: [{
            required: true,
            message: '请输入模板名称',
            trigger: 'blur'
          }],
          score: [{
            required: true,
            message: '请选择评分项',
            trigger: 'change'
          }],
          // CHANNELTYPE: [{
          //   required: true,
          //   message: '请选择渠道类型',
          //   trigger: 'change'
          // }],
          // BUSINESSTYPE: [{
          //   required: true,
          //   message: '请输入业务类型',
          //   trigger: 'blur'
          // }]
        },
        loading: false,
      };
    },
    created() {

    },
    methods: {
      //表格单元格合并
      objectSpanMethod({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        if (columnIndex === 0 || columnIndex === 1) {
          if (this.spanArr[rowIndex] && columnIndex != 2) {
            return {
              rowspan: this.spanArr[rowIndex],
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
      dataFormat(row, column) {
        //枚举设备形式
        if (column.property == "SPECIALATTRIBUTE")
          return this.special[row[column.property]];
        if (column.property == "MINORTERMTYPE")
        return this.typeOption[row[column.property]];
      },
      dealOption() {

      },
      // 查询评分大项
      async dataQueryBig() {
        let resBody = new scoreDictionaryBigQuery();
        resBody.data.CurrPage = 1
        resBody.data.PageRowNum = 500
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.scoreOptionBig = response.BODY.REQBODY;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 查询评分子项
      async dataQuerySmall() {
        let resBody = new scoreDictionarySmallQuery();
        resBody.data.CurrPage = 1
        resBody.data.PageRowNum = 500
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.scoreOptionSmall = response.BODY.REQBODY;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 改变评分项的时候触发
      changeScore() {
        let arr = []
        this.ruleForm.score.forEach(item => {
          arr.push({
            SCOREMAJORITEMID: item[0],
            SCOREMAJORITEMNAME: this.searchBigName(item[0]),
            SCOREMAJORITEMWEIGHT: '',
            SCOREMINORTERMID: item[1],
            SCOREMINORTERMNAME: this.searchSmall(item[1], 1),
            SCOREMINORTERMWEIGHT: '', //小项权重
            SPECIALATTRIBUTE: this.searchSmall(item[1], 2), //评分子项属性
            SUBSIDIARYFIELD: this.searchSmall(item[1], 3), //特殊项附属字段
            SUBSIDIARYFIELDFS: this.searchSmall(item[1], 4), //特殊项附属字段对应分数
            EXTRASCORE: this.searchSmall(item[1], 5), //额外分值
            MINORTERMTYPE: this.searchSmall(item[1], 6), //评分子项类型
          })
        })
        this.tableData = arr
        this.spanArr = [];
        let contactDot = 0;
        this.tableData.forEach((info, index) => {
          if (index - 1 >= 0 && info.SCOREMAJORITEMNAME === this.tableData[index - 1].SCOREMAJORITEMNAME) {
            this.spanArr[contactDot] += 1;
            this.spanArr.push(0)
          } else {
            contactDot = index
            this.spanArr.push(1)
          }
        });
      },
      searchBigName(row) {
        let name = ''
        this.option.scoreOptionBig.forEach(item => {
          if (item.SCOREMAJORITEMID == row) {
            name = item.SCOREMAJORITEMNAME
          }
        })
        return name
      },
      searchSmall(row, value) {
        let name = ''
        this.option.scoreOptionSmall.forEach(item => {
          if (value == 1) {
            item.SCOREMINORTERMID == row ? name = item.SCOREMINORTERMNAME : ''
          }
          if (value == 2) {
            item.SCOREMINORTERMID == row ? name = item.SPECIALATTRIBUTE : ''
          }
          if (value == 3) {
            item.SCOREMINORTERMID == row ? name = item.SUBSIDIARYFIELD : ''
          }
          if (value == 4) {
            item.SCOREMINORTERMID == row ? name = item.SUBSIDIARYFIELDFS : ''
          }
          if (value == 5) {
            item.SCOREMINORTERMID == row ? name = item.EXTRASCORE : ''
          }
          if (value == 6) {
            item.SCOREMINORTERMID == row ? name = item.SCOREMINORTERMTYPE : ''
          }
        })
        return name
      },
      openDialog() {
        if (this.option.flag == 'add') {
          this.tableData = []
          this.spanArr = []
          this.ruleForm = {
            SCORETEMPLATEID: '',
            SCORETEMPLATENAME: '',
            // BUSINESSTYPE: '',
            // CHANNELTYPE: '',
            CREATIVEPERSON: this.$store.getters.UserNum, //创作人
            score: []
          }
        } else {
          this.updateOption()
        }
      },
      updateOption() {
        this.ruleForm.SCORETEMPLATEID = this.option.row.SCORETEMPLATEID
        this.ruleForm.SCORETEMPLATENAME = this.option.row.SCORETEMPLATENAME
        // this.ruleForm.BUSINESSTYPE = this.option.row.BUSINESSTYPE
        // this.ruleForm.CHANNELTYPE = this.option.row.CHANNELTYPE
        let arr = []
        let data = []
        this.option.row.DTL1.forEach(item => {
          item.DTL2.forEach(el => {
            data.push({
              SCOREMAJORITEMID: item.SCOREMAJORITEMID,
              SCOREMAJORITEMNAME: item.SCOREMAJORITEMNAME,
              SCOREMAJORITEMWEIGHT: item.SCOREMAJORITEMWEIGHT,
              SCOREMINORTERMNAME: el.SCOREMINORTERMNAME,
              SCOREMINORTERMID: el.SCOREMINORTERMID,
              MINORTERMTYPE: el.MINORTERMTYPE,
              SCOREMINORTERMWEIGHT: el.SCOREMINORTERMWEIGHT,
              SPECIALATTRIBUTE: el.SPECIALATTRIBUTE,
              SUBSIDIARYFIELD: el.SUBSIDIARYFIELD,
              SUBSIDIARYFIELDFS: el.SUBSIDIARYFIELDFS,
              EXTRASCORE: el.EXTRASCORE,
            })
            arr.push([item.SCOREMAJORITEMID, el.SCOREMINORTERMID])
          })
        })
        this.ruleForm.score = arr
        this.tableData = data
        this.spanArr = [];
        let contactDot = 0;
        this.tableData.forEach((info, index) => {
          if (index - 1 >= 0 && info.SCOREMAJORITEMNAME === this.tableData[index - 1].SCOREMAJORITEMNAME) {
            this.spanArr[contactDot] += 1;
            this.spanArr.push(0)
          } else {
            contactDot = index
            this.spanArr.push(1)
          }
        });
      },
      closeDialog() {
        if (this.$refs['ruleForm'] != undefined) {
          this.$refs['ruleForm'].clearValidate();
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let arr = []
            this.tableData.forEach(item => {
              var oldObj = {
                SCOREMAJORITEMNAME: item.SCOREMAJORITEMNAME,
                SCOREMAJORITEMWEIGHT: item.SCOREMAJORITEMWEIGHT,
                DTL2: []
              }
              var DTL2 = {
                SCOREMINORTERMNAME: item.SCOREMINORTERMNAME,
                MINORTERMTYPE: item.MINORTERMTYPE,
                SCOREMINORTERMWEIGHT: item.SCOREMINORTERMWEIGHT,
                SPECIALATTRIBUTE: item.SPECIALATTRIBUTE,
                SUBSIDIARYFIELD: item.SUBSIDIARYFIELD,
                SUBSIDIARYFIELDFS: item.SUBSIDIARYFIELDFS,
                EXTRASCORE: item.EXTRASCORE,
              }
              oldObj.DTL2.push(DTL2)
              arr.push(oldObj)
            })
            /**
             * 先去重，后合并
             * 1、源数据去重
             * 2、把去重后的数据和源数据中相同大项的数据合并DTL2
             */
            var newData = []
            var newObj = {}
            arr.forEach((el, i) => {
              if (!newObj[el.SCOREMAJORITEMNAME]) {
                newData.push(el);
                newObj[el.SCOREMAJORITEMNAME] = true;
              } else {
                newData.forEach(el => {
                  if (el.SCOREMAJORITEMNAME === arr[i].SCOREMAJORITEMNAME) {
                    el.DTL2 = el.DTL2.concat(arr[i].DTL2);
                    // el.citys = [...el.citys, ...oldDataRule[i].citys]; // es6语法
                  }
                })
              }
            })
            // 验证
            let weightFlag = true
            let bigWeight = 0
            let smallFlag = true
            // let smallWeight = 0
            newData.forEach(item => {
              if (item.SCOREMAJORITEMWEIGHT == '') {
                weightFlag = false
                return
              }
              if(smallFlag==false || weightFlag==false){
                return 
              }
              bigWeight += Number(item.SCOREMAJORITEMWEIGHT)
              let smallWeight = 0
              item.DTL2.forEach(el => {
                if (el.SCOREMINORTERMWEIGHT == '') {
                  weightFlag = false
                  return
                }
                smallWeight += Number(el.SCOREMINORTERMWEIGHT)
              })
              if (smallWeight != 100) {
                console.log(smallWeight)
                smallFlag = false
                return
              }
            })
            if (weightFlag == false) {
              this.$message.error('请输入评分项权重值')
              return
            }
            if (smallFlag == false) {
              this.$message.error('每个评分大项中评分子项的权重值的和需为100，请重新选择！')
              return
            }
            if (bigWeight != 100) {
              this.$message.error('评分大项权重值的和需为100，请重新选择！')
              return
            }
            let resBody
            resBody = this.option.flag == 'add' ? new addTemp() : new updateTemp();
            if (this.option.flag == 'update') {
              resBody.data.SCORETEMPLATEID = this.ruleForm.SCORETEMPLATEID
            }
            resBody.data.SCORETEMPLATENAME = this.ruleForm.SCORETEMPLATENAME
            // resBody.data.BUSINESSTYPE = this.ruleForm.BUSINESSTYPE
            // resBody.data.CHANNELTYPE = this.ruleForm.CHANNELTYPE
            resBody.data.CREATIVEPERSON = this.ruleForm.CREATIVEPERSON
            resBody.data.DTL1 = newData
            let response = await request(resBody);
            if (response.SYS_HEAD.ReturnCode == "000000") {
              if (this.option.flag == 'update') {
                this.$message({
                  type: 'success',
                  message: '修改成功！'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: '新增成功！'
                })
              }
              this.isShow = false;
              this.$emit("refreshTable");
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD
                  .ReturnMessage
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].clearValidate();
          this.$refs[formName].resetFields();
        }
      }
    }
  };

</script>

<style scoped>

</style>
